package com.nulstudio.sppm.Controller;

import com.alibaba.fastjson2.JSONObject;
import com.nulstudio.sppm.Annotation.NormalJwt;
import com.nulstudio.sppm.Entities.UserInfo;
import com.nulstudio.sppm.Service.UserInfoService;
import com.nulstudio.sppm.Utils.EncodingUtils;
import com.nulstudio.sppm.Utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Controller
@CrossOrigin(value = "*")
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserInfoService userInfoService;

    @PostMapping(value="/loginpage",produces="application/json;charset=UTF-8")
    public String login(@RequestBody Map<String,String> map){
        JSONObject json = new JSONObject();
        if(map.containsKey("account") && map.containsKey("password")) {
            final String account =map.get("account");
            final String password = map.get("password");
            if (!userInfoService.checkExisted(account)) {
                json.put("code",200);
                json.put("message", "nonexistent account");
                json.put("version",1);
                return json.toJSONString();
            }
            if (userInfoService.checkMatched(account,password)) {
                final UserInfo userInfo = userInfoService.getInfoByAccount(account);
                String token = JwtUtils.sign(String.valueOf(userInfo.getUid()),userInfo.getAuthority());
                json.put("code", 0);
                json.put("message", "");
                json.put("version", 1);
                JSONObject result = new JSONObject();
                result.put("token", token);
                result.put("authority", userInfo.getAuthority());
                json.put("result", result);
                return json.toJSONString();
            }
            json.put("code",201);
            json.put("message", "unmatched password");
            json.put("version",1);
            return json.toJSONString();
        }
        json.put("code",202);
        json.put("message","cant get account and pwd");
        json.put("version",1);
        return json.toJSONString();
    }

    @PostMapping(value="/check",produces="application/json;charset=UTF-8")
    public String check(@RequestBody Map<String, String> params) {
        final String token = params.get("token");
        boolean valid = true;
        try {
            JwtUtils.checkSign(token);
        } catch (RuntimeException e) {
            e.printStackTrace();
            valid = false;
        }
        JSONObject json = new JSONObject();
        json.put("code", 0);
        json.put("message", "");
        json.put("version", 1);
        JSONObject result = new JSONObject();
        result.put("valid", valid);
        json.put("result", result);
        return json.toJSONString();
    }
}
